package com.xy.rpcTest;

import org.junit.Test;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class 压缩 {

    @Test
    public void test1() throws IOException {
        // 压缩
        byte[] bytes1 = new byte[]{
                1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
                1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
                1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
                1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
                1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
                1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
                1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
                1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
                1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
                1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
                1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20};

        // 将bytes1作为输入, 将结果输出的到另一个字节数组当中
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream);
        gzipOutputStream.write(bytes1);
        gzipOutputStream.finish();

        byte[] bytes2 = byteArrayOutputStream.toByteArray();

        // 输出bytes1, bytes2, 看看结果
        System.out.println("原数据: ---> " + Arrays.toString(bytes1));
        System.out.println("压缩后: ---> " + Arrays.toString(bytes2));

        // 长度对比
        System.out.println("bytes1.length = "+ bytes1.length);
        System.out.println("bytes2.length = "+ bytes2.length);
    }

    // 解压缩示例
    @Test
    public void test2() throws IOException {
        // 压缩
        byte[] bytes1 = new byte[]{
                31, -117, 8, 0, 0, 0, 0, 0, 0, -1, 99, 100, 98, 102, 97, 101, 99,
                -25, -32, -28, -30, -26, -31, -27, -29, 23, 16, 20, 18, 22, 97,
                28, 38, 98, 0, -75, 54, 52, 86, -36, 0, 0, 0};

        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes1);
        GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream);
        byte[] bytes2 = gzipInputStream.readAllBytes();

        // 输出bytes1, bytes2, 看看结果
        System.out.println("压缩数据: ---> " + Arrays.toString(bytes1));
        System.out.println("解压缩后: ---> " + Arrays.toString(bytes2));

        // 长度对比
        System.out.println("bytes1.length = "+ bytes1.length);
        System.out.println("bytes2.length = "+ bytes2.length);
    }

}

